﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NetworkAssetManager.Entity;
using System.Management;
using log4net;

namespace NetworkAssetManager.WMI
{
    class Bios
    {
        private static readonly ILog _logger = LogManager.GetLogger(typeof(Bios));

        private static EntBios FillDetails(ManagementBaseObject obj)
        {
            EntBios objEntBios = new EntBios();
            try
            {
                objEntBios.ReleaseDate = WMIUtil.ToDateTime((string)obj["ReleaseDate"]);
            }
            catch (Exception)
            {
                objEntBios.ReleaseDate = DateTime.MinValue;
            }
            
            try
            {
                objEntBios.Manufacturer = WMIUtil.ToString(obj["Manufacturer"]);
            }
            catch (Exception)
            {
                objEntBios.Manufacturer = "";
            }

            try
            {
                objEntBios.Version = WMIUtil.ToString(obj["SMBIOSBIOSVersion"]);
            }
            catch (Exception)
            {
                objEntBios.Version = ""; 
            }

            return objEntBios;
        }
        public static List<EntBios>GetBiosDetails(ManagementScope scope)
        {
            _logger.Info("Collecting Bios details for machine " + scope.Path.Server);

            ObjectQuery query = null;
            ManagementObjectSearcher searcher = null;
            ManagementObjectCollection objects = null;
            List<EntBios> lstBios = new List<EntBios>(); 
            
            try
            {
                query = new ObjectQuery("Select * from Win32_BIOS");
                searcher = new ManagementObjectSearcher(scope, query);
                objects = searcher.Get();
                lstBios.Capacity = objects.Count;
                foreach (ManagementBaseObject obj in objects)
                {
                    lstBios.Add(FillDetails(obj));
                    obj.Dispose();
                }
            }
            catch (Exception e)
            {
                _logger.Error("Exception is Bios collection "+ e.Message); 
            }
            finally
            {
                searcher.Dispose();
            }
            return lstBios;
        }
    }
}
